﻿using System;
using System.Data.SQLite;
using System.IO;
using Fortune.Context;
using Fortune.Log;
using UnityEngine;

namespace Fortune.Loader
{
    /// <summary>
    /// 数据库初始化加载器，在没有数据库时，读取配置文件对数据库进行初始化
    /// </summary>
    public static class DatabaseInitLoader
    {
        private static readonly FortuneLogger logger = FortuneLogger.newInstance(typeof(DatabaseInitLoader));
        
        public static void load()
        {
            string initSqlPath = FortuneContext.fortuneBepInExConfig.initSqlPath.Value;
            string databasePath = FortuneContext.fortuneBepInExConfig.dataBasePath.Value;
            
            if (File.Exists(databasePath))
            {
                logger.info($"数据库已存在，无需初始化：{databasePath}");
                return;
            }
            
            if (!File.Exists(initSqlPath))
            {
                logger.error($"初始化SQL文件不存在: {initSqlPath}");
                throw new FileNotFoundException($"初始化SQL文件不存在: {initSqlPath}");
            }

            try
            {
                SQLiteConnection.CreateFile(databasePath);
                using (SQLiteConnection connection = new SQLiteConnection(FortuneContext.connectionUrl))
                {
                    connection.Open();
                    SQLiteCommand initCommand = new SQLiteCommand(File.ReadAllText(initSqlPath), connection);
                    initCommand.ExecuteNonQuery();
                    connection.Close();
                }
            }
            catch (Exception e)
            {
                logger.error("数据库初始化异常", e);
                throw;
            }
        }
    }
}